package com.tanhua.mongodbManager.controller;

import com.tanhua.mongodbManager.domain.db.User;
import com.tanhua.mongodbManager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName -> UserController
 * @Description
 * @Author OHC
 * @Date 2021/8/18 星期三
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    /**
     * 登录功能
     */
    @PostMapping("/login")
    public ResponseEntity<Object> login(@RequestBody User user, HttpSession session) {
        String adminName = user.getAdminName();
        String password = user.getPassword();
        //获取用户对象
        User login = userService.login(adminName, password);
        Map<String, Object> resultMap = new HashMap<>();
        //判断是否登录成功
        if (login != null) {
            //登录成功
            session.setAttribute("user", login);
            resultMap.put("success", true);
            resultMap.put("message", "登录成功");
        }else {
            //登录失败
            resultMap.put("success", false);
            resultMap.put("message", "登录失败，请重试");
        }
        return ResponseEntity.ok(resultMap);
    }

    /**
     * 用户退出
     */
    @GetMapping("/logout")
    public void logout(HttpSession session) {
        //会话过期
        session.invalidate();
    }

}
